package com.lcxw.hxzbadmin.controller.dbcontroller;

import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbadmin.service.dbmanagerservice.DbManagerService;
import com.lcxw.hxzbapi.entity.response.Response;

@RestController
@RequestMapping("/admin/database")
@CrossOrigin
public class DbManagerController {
    private Logger logger = LoggerFactory.getLogger(DbManagerController.class);

    @Resource
    DbManagerService dbManagerService;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    DbOperation dbOperation;

    /**
     * 1、浏览数据库
     * @return Response
     */
    @PostMapping("/view")
    public Response viewDb(@RequestBody JSONObject requestParams){
        List<String> tableNames = dbManagerService.selectAllTables();

        List<JSONObject> data = new ArrayList<>();

        for (String tableName:tableNames
        ) {

            Map<String,Integer> tableInfo = dbManagerService.selectTableSize(tableName);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tableName",tableName);
            jsonObject.put("size",tableInfo.get("size"));
            jsonObject.put("free",tableInfo.get("free"));

            data.add(jsonObject);

        }

        return Response.ok(data);

    }

    /**
     * 2、优化数据库表碎片
     */
    @PostMapping("/optimize")
    public Response optimizeDb(@RequestBody JSONObject requestParams){
        String tableName = requestParams.getString("tableName");
        logger.info("admin {} optimize table:{}",requestParams.getString("adminName"),tableName);

        String sql = "alter table " + tableName + " engine=innodb";

        jdbcTemplate.update(sql);

        return Response.ok();
    }

    /**
     * 3、备份数据库接口
     */
    @PostMapping("/backup")
    public Response backupDb(@RequestBody JSONObject requestParams){
        String adminName = requestParams.getString("adminName");
        String tableName = requestParams.getString("tableName");
        logger.info("admin {} backup db table: {}",adminName,tableName);
        dbOperation.backupTable(tableName);
        return null;
    }

}
